package com.bw.title.util;

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.exception.FdfsUnsupportStorePathException;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * @Author: FanYangJie
 * @BelongsProject: search-house
 * @BelongsPackage: com.bw.utils
 * @Date: 2023/11/10 20:27
 * @Description: TODO
 */
@Component
public class FastFileUtils {
    @Autowired
    private FastFileStorageClient storageClient;

    private  String serverUrl="http://172.27.6.142:8888/";

    /**
     * @deprecated: TODD 文件上传
     * @Author: FAnYangJie〔^.べ〕γ
     * @Date: 2023/11/10 20:31
     */
    public  String uploadFile(MultipartFile file) throws IOException {
        StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize()
                , FilenameUtils.getExtension(file.getOriginalFilename()), null);
        return  getResAccessurl(storePath);
    }

    /**
     * @deprecated: TODD 普通的文件上传
     * @Author: FAnYangJie〔^.べ〕γ
     * @Date: 2023/11/10 21:38
     */
    public  String uploadFile(File file) throws FileNotFoundException {
        FileInputStream inputStream = new FileInputStream(file);
        StorePath path = storageClient.uploadFile(inputStream, file.length(),
                FilenameUtils.getExtension(file.getName()), null);
        return  getResAccessurl(path);
    }

    /**
     * @deprecated: TODD 输入流姓氏的进行文件上传
     * @Author: FAnYangJie〔^.べ〕γ
     * @Date: 2023/11/10 21:35
     */
    public  String uploadFileStream(InputStream is, long size,String fileName){
        StorePath path = storageClient.uploadFile(is, size, fileName, null);
        return getResAccessurl(path);
    }

    /**
     * @deprecated: TODD  返回上传地址
     * @Author: FAnYangJie〔^.べ〕γ
     * @Date: 2023/11/10 21:29
     */
    public  String getResAccessurl(StorePath storePath){
        String fileUrl=serverUrl+storePath.getFullPath();
        return  fileUrl;
    }

    /**
     * @deprecated: TODD 删除文件
     * @Author: FAnYangJie〔^.べ〕γ
     * @Date: 2023/11/10 21:32
     */
    public  void deleteFile(String fileUrl){
        if (StringUtils.isEmpty(fileUrl)) {
            return;
        }
        try {
            StorePath storePath = StorePath.parseFromUrl(fileUrl);
            storageClient.deleteFile(storePath.getGroup(),storePath.getPath());
        }catch (FdfsUnsupportStorePathException e){
            e.printStackTrace();
        }
    }
}
